/* eslint-disable @typescript-eslint/ban-ts-comment */
type LocationType = {
  latitude: number;
  longitude: number;
  location: string;
};

export const useLocation = async (): Promise<LocationType> => {
  let latitude: number;
  let longitude: number;

  try {
    const position = await getCurrentPosition();
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
    return Promise.resolve({
      latitude,
      longitude,
      location: `${latitude}:${longitude}`
    });
  } catch (error) {
    console.log(`获取位置信息失败：${error?.message}`);
    // @ts-expect-error
    window.$message.error(error?.message);
    // 默认值处理
    latitude = 0;
    longitude = 0;
    return Promise.resolve({
      latitude,
      longitude,
      location: `${latitude}:${longitude}`
    });
  }
};

function getCurrentPosition(): Promise<GeolocationPosition> {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject);
  });
}
